/*********************************************************
          File Name:client.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Sat 20 Jun 2015 02:30:54 PM CST
**********************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "../sock.h"
#include <sys/wait.h>
#include <sys/time.h>
#include <errno.h>

void child(char *host, char *port)
{
    int sockfd = 0;
    int res = 0;
    char buf[10] = {'\0'};
    sockfd = mysocket(CLIENT, host, port, 5, NULL);

    if(sockfd == -1)
    {
        perror("mysocket()");
        exit(1);
    }
    if(write(sockfd,"0", 1) == -1)
        perror("write()");
    errno = 0;
    if((res = read(sockfd, buf, 5)) < 0)
        perror("read()");
    else
        printf("read: %d bytes\t%s\n",res, buf);
}
    

int main(int argc, char *argv[])
{
        if(argc != 4)
        {
                fprintf(stderr, "%s host port clients\n", argv[0]);
                exit(1);
        }
        int i;
        struct timeval start, end;
        gettimeofday(&start, NULL);
    for(i = 0; i < atoi(argv[3]); i++)
    {
        switch(fork())
        {
            case -1:
                perror("fork()");
                exit(1);
            case 0:
                child(argv[1], argv[2]);
                _exit(1);
            default:
                break;
        }
    }

    while(wait(NULL) != -1)
        continue;
        gettimeofday(&end, NULL);
        printf("time %lf s\n", (double)(end.tv_sec - start.tv_sec) +
                        ((double)(end.tv_usec - start.tv_usec))/ 1000000);

    return 0;
}
